//
//  AddUserViewController.m
//  FlowerRainGround
//
//  Created by zfc on 16/4/27.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "AddUserViewController.h"
#import "UserInfoModel.h"
#import "SearchTableViewCell.h"
#import "FactoryTableViewCell.h"
#import "UserInfoViewController.h"

@interface AddUserViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate>


@property (nonatomic, copy)NSString *keywords; //从搜索框获取的搜索关键字

@property (nonatomic, strong)NSMutableArray *dataArray;//推荐用户数组

@property (nonatomic, strong)NSMutableArray *JianArray;//推荐数据数组

@property (nonatomic, strong)UITableView *tableView;//显示数据的表视图

@property (strong, nonatomic)UISearchController *searchController;//搜索控制器

@property (nonatomic, strong) NSMutableArray *dataArr; //表视图数组

@property (nonatomic, strong) UILabel *label;//推荐用户的label


@end

@implementation AddUserViewController

- (void)dealloc {
NSLog(@"%@ dealloc",NSStringFromClass([self class]));

}

#pragma mark --- 懒加载 ---
- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}


- (NSMutableArray *)JianArray {
    
    if (!_JianArray) {
        self.JianArray = [NSMutableArray array];
    }
    
    return _JianArray;
}

- (NSMutableArray *)dataArr {
    
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}

//搜索控制器的创建
- (UISearchController *)searchController {
    
    if (!_searchController) {
        
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchBar.delegate = self;
        _searchController.hidesNavigationBarDuringPresentation = NO;
        _searchController.searchBar.placeholder = @"搜索";
        [_searchController.searchBar sizeToFit];
        
    }
    
    return _searchController;
    
}

#pragma mark --- 数据请求 ---


//请求搜索的用户信息
- (void)handleAddAttentionData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://app.htxq.net/servlet/UserCustomerServlet?currentPageIndex=0&action=searchUser&pageSize=20" parameters:@{@"userId":[userManager getUsrID],@"keywords":self.keywords} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"++++++++%@",dataDic);
        
        [self.dataArray removeAllObjects];
        NSArray *array = dataDic[@"result"];
        for (NSDictionary *dic in array) {
            
            UserInfoModel *model = [[UserInfoModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            
        }
//        NSLog(@"*****%@", self.dataArray);

        _dataArr = _dataArray;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.tableView.frame = CGRectMake(0, 44, kWidth, kHeight-64-44);
            [self.label removeFromSuperview];
            [self.tableView reloadData];
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        
    }];
    
    
}

//获取推荐数据
- (void) handleJianData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://app.htxq.net/servlet/UserCustomerServlet?action=getJianUserList&currentPageIndex=0&pageSize=20" parameters:@{@"userId":[userManager getUsrID]} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"————————%@",dataDic);
        
        [self.JianArray removeAllObjects];
        NSArray *array = dataDic[@"result"];
        
        for (NSDictionary *dic in array) {
            
            UserInfoModel *model = [[UserInfoModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.JianArray addObject:model];
            
        }
        
        
        self.dataArr = self.JianArray;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 44, kWidth, 40)];
            _label.text = @"推荐用户";
            [self.view addSubview:_label];
            self.tableView.frame = CGRectMake(0, 84, kWidth, kHeight-64-84);
            [self.tableView reloadData];

        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        
    }];

}

//点击返回的时候先取消键盘并移除搜索框
- (void)back {
    
    [self.searchController.searchBar resignFirstResponder];
    
    [self.searchController.searchBar removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    [self createJianTableView];
    self.navigationItem.title = @"添加关注";
    self.keywords = self.searchController.searchBar.text;
    
    [self handleJianData];
    
}



#pragma mark --- 视图创建 ---

//创建tableView
- (void)createJianTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, kWidth, kHeight-64-44)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([UserInfoModel class])];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.searchController.searchBar];
}

#pragma mark --- tableView代理和数据源方法 ---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return self.dataArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BaseModel *model = nil;
    model = self.dataArr[indexPath.row];

    BaseTableViewCell *cell = [FactoryTableViewCell createTableViewCellWithModel:model tableView:self.tableView indexPath:indexPath];
        [cell setDataWithModel:model];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 90;
    
}

//点击cell跳转到用户资料界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - UISearchDelegate

//当输入框内的text改变时的方法回调
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    self.keywords = searchBar.text;
    [self handleAddAttentionData];
    
}

//点击键盘上搜索按钮触发的方法
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    //搜索框放弃编辑 --- 光标消失
    [self.searchController.searchBar endEditing:YES];

    //搜索框取消第一焦点 --- 键盘消失
    [self.searchController.searchBar resignFirstResponder];

    self.keywords = searchBar.text;
    if (self.keywords == nil) {
        
        [self handleJianData];
        
    } else {
        
        [self handleAddAttentionData];
        
    }
    
    //取消搜索框的活跃状态 --在活跃状态视图为透明灰色
    self.searchController.active = NO;
    
}


//取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    if ([self.searchController.searchBar.text isEqualToString:@" "]) {
        return;
    }else{
    [self.label removeFromSuperview];
        [self handleJianData];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little pr
 eparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
